package com.coocaa.ops.admin.base.util;

import com.coocaa.ops.admin.base.constant.SessionConstants;
import com.coocaa.ops.common.core.base.model.SimpleSysUserInfo;
import com.coocaa.ops.common.core.biz.auth.entity.SysUserEntity;
import com.coocaa.ops.common.tool.exception.LoginException;
import com.coocaa.ops.common.tool.http.HttpSessionUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * @author bijiahao
 * @date : 2019/6/14.
 * @description web用户会话信息获取工具
 */
public class WebUtil {
    /**
     * 当前用户信息-原始数据
     *
     * @param request
     * @return
     */
    public static SysUserEntity getCurrentUser(HttpServletRequest request) {
        if (isDebug(request)) {
            return getSysUserDebug();
        }
        SysUserEntity user = (SysUserEntity) HttpSessionUtil.getSessionValue(request, SessionConstants.SESSION_LOGIN_USER);
        if (user != null) {
            return user;
        }
        throw new LoginException("Please login first");
    }

    public static SysUserEntity getUserForLogOpRecord(HttpServletRequest request) {
        Object userObj = HttpSessionUtil.getSessionValue(request, SessionConstants.SESSION_LOGIN_USER);
        if (null != userObj) {
            return (SysUserEntity) userObj;
        }
        return null;
    }

    public static SysUserEntity getSysUserDebug() {
        SysUserEntity sysUserEntity = new SysUserEntity();
        sysUserEntity.setUserName("JustTest");
        return sysUserEntity;
    }

    public static boolean isSwagger(HttpServletRequest request) {
        String headerVal = request.getHeader(SessionConstants.X_AUTH_TOKEN);
        if (SessionConstants.X_AUTH_TOKEN_VAl.equals(headerVal)) {
            return true;
        }
        String referer = request.getHeader("Referer");
        if (StringUtils.isNotBlank(referer) && referer.contains("swagger-ui.html")) {
            return true;
        }
        return false;
    }

    /**
     * 是否debug调试
     * <p>
     * 测试代码时, 请求参数<code>debug</code>为1,则为true
     *
     * @param request
     * @return
     */
    private static boolean isDebug(HttpServletRequest request) {
        return "1".equals(request.getParameter("debug"))
                || isSwagger(request)
                ;
    }
}
